package com.pansoft.openplanet.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.efounder.utils.ResStringUtil;
import com.pansoft.newasset.event.OptionMarketEvent;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.WalletAvatarAndNameSetupActivity;
import com.pansoft.openplanet.activity.WalletTypeSelectActivity;
import com.pansoft.openplanet.adapter.ChildWalletListAdapter;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.StarAssetWalletPopup;
import com.pansoft.openplanet.widget.WrapContentLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ETHWalletListFragment extends BaseFragment implements View.OnClickListener {

    public static final String TAG = "ETHWalletListFragment";

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ChildWalletListAdapter childWalletListAdapter;
    private ArrayList<AssetListBean> assetList = new ArrayList<>();//当前关注的代币列表
    private int mode = IPAssetsConstant.CHAIN_ID_ETH;
    private String balance = "0";//钱包余额

    private LinearLayout llEmptyLayout;
    private Button tvCreateWallet;
    private Button tvRestoreWallet;
    private ImageView ivIcon;
    private TextView tvTextTitle;


    public ETHWalletListFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_fragment_wallet_list, container, false);

        initView(rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        EFHttpRequest.cancelRequest(TAG);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWalletChanged(Account account) {
        initData();
    }

    private void initView(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        llEmptyLayout = (LinearLayout) rootView.findViewById(R.id.ll_empty_layout);
        tvCreateWallet = (Button) rootView.findViewById(R.id.tv_create_wallet);
        tvRestoreWallet = (Button) rootView.findViewById(R.id.tv_restore_wallet);
        ivIcon = (ImageView) rootView.findViewById(R.id.iv_icon);
        tvTextTitle = (TextView) rootView.findViewById(R.id.tv_text_title);
        tvRestoreWallet.setOnClickListener(this);
        tvCreateWallet.setOnClickListener(this);

        childWalletListAdapter = new ChildWalletListAdapter(getContext(), assetList, mode);
        recyclerView.setAdapter(childWalletListAdapter);
        initSwipeRefreshView(rootView);
    }

    /**
     * 初始化下拉刷新
     */
    private void initSwipeRefreshView(View rootView) {
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                initData();
            }
        });
    }

    private void initData() {
        //请求钱包余额
        AccountDao accountDao = new AccountDao(getActivity());
        Account account = accountDao.getCurrentShowAccount(IPAssetsConstant.ChainEnum.ETH);
        if (account == null) {
            List<Account> accounts = accountDao.getAllChildAccount(IPAssetsConstant.ChainEnum.ETH);
            if (accounts.size() == 0) {
                refreshLayout.setVisibility(View.GONE);
                llEmptyLayout.setVisibility(View.VISIBLE);
                ivIcon.setImageDrawable(getResources().getDrawable(R.drawable.ipasset_wallet_list_eth));
                tvTextTitle.setText("ETH");
                return;
            } else {
                account = accounts.get(0);
                account.setCurrentShow(true);
                accountDao.insertOrReplace(account);
                refreshLayout.setVisibility(View.VISIBLE);
                llEmptyLayout.setVisibility(View.GONE);
            }
        }
        String address = account.getAddress();
        //requestWalletBalance(address);
        requestAttentionTokenData(address);
    }

    /**
     * 请求关闭的代币数据
     *
     * @param address
     */
    private void requestAttentionTokenData(String address) {
        assetList.clear();
        //添加头部区域
        assetList.add(new AssetListBean.Builder().type(1).build());
        //添加第一条数据eth
        assetList.add(new AssetListBean.Builder().build());
        childWalletListAdapter.notifyDataSetChanged();
        HashMap<String, String> params = new HashMap<>();
        params.put("chainID", IPAssetsConstant.CHAIN_ID_ETH + "");//链编号，BTC传1，ETC传2
        params.put("userAddress", address);//用户钱包地址
        TCRequestUtil.getCommonRequest(TAG, "chain/getAllTokenBalanceByChainAndUserAddress",
                params, new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {

                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("result").equals("success")) {
                                balance = jsonObject.optString("AddressBalance", "0");
                                if ("0".equals(balance) || "".equals(balance)) {
                                    childWalletListAdapter.setData("0");
                                } else {
                                    balance = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                                    //将余额传给adapter，部分刷新界面，显示头部余额和第一项余额
                                    childWalletListAdapter.setData(balance);
                                }
                                //解析代币数据
                                JSONArray jsonArray = jsonObject.optJSONArray("AllTokenBalance");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject walletObject = jsonArray.getJSONObject(i);
                                        AssetListBean assetListBean = new AssetListBean.Builder()
                                                .address(walletObject.optString("tokenAddress"))
                                                .icon(walletObject.optString("tokenIcon"))
                                                .name(walletObject.optString("tokenName"))
                                                .secondName(walletObject.optString("tokenFullName"))
                                                .balance(walletObject.optString("balance"))
                                                .id(walletObject.optString("tokenID"))
                                                .blockChainID(walletObject.optString("blockChainID"))
                                                .tokenDecimals(walletObject.optInt("tokenDecimals"))
                                                .isSelected(walletObject.optBoolean("isSelected"))
                                                .build();
                                        assetList.add(assetListBean);
                                    }
                                }
                                childWalletListAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                        }
                        refreshLayout.finishRefresh();
                    }

                    @Override
                    public void onFail(String error) {
                        refreshLayout.finishRefresh();
                        ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    }
                });
    }

    /**
     * 请求钱包余额
     *
     * @param address 钱包地址
     */
    @Deprecated
    private void requestWalletBalance(String address) {
        HashMap<String, String> map = new HashMap<>();
        map.put("ethAddress", address);
        TCRequestUtil.postCommonRequest(TAG, "eth/ethGetBalance", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                JSONObject jsonObject = null;

                try {
                    jsonObject = new JSONObject(response);
                    if (jsonObject != null && jsonObject.getString("result").equals("success")) {
                        String rawBalance = jsonObject.getString("balance");
                        balance = BalanceUtil.balanceConvert(rawBalance);
                        //将余额传给adapter，部分刷新界面，显示头部余额和第一项余额
                        childWalletListAdapter.setData(balance);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_create_wallet) {
            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_CREATE_NEW,
                    IPAssetsConstant.CHAIN_ID_ETH);
        } else if (id == R.id.tv_restore_wallet) {
            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_RESTORE_OLD,
                    IPAssetsConstant.CHAIN_ID_ETH);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rightTopMenuClickEvent(RightTopMenuClickEvent event) {
        StubObject stubObject = (StubObject) event.getStubObject();
        String id = stubObject.getObject("id", "").toString();
        if (id.equals("eth")) {
            //StarAssetWalletPopup.showPopup(getActivity(), event.getView(), "eth");
            StarAssetWalletPopup.showPopup(getActivity(), event.getView(), IPAssetsConstant.CHAIN_ID_ETH);

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void optionalMarketDataEvent(OptionMarketEvent event){
        if(childWalletListAdapter!=null){
            childWalletListAdapter.setOptionMarketData(event.getKlineOptionalOrMVModels().get(0));
        }
    }

}
